﻿using System.Collections.Generic;
using UnityEngine;

namespace UFrame
{
    public class OUMovePoint : MonoBehaviour
    {
        [Header("移动的点")] public List<Transform> pointList = new List<Transform>();

        [HideInInspector] public int index = 0;
        [Header("速度")] public float speed = 3;
        public float reachDistance = 0.5f;
        public bool isLoop = false;
        [Header("启动移动")] public bool isMoveSus = true;
        [Header("面向目标点")] public bool isFaceTarget = false;

        public bool isIgnoreYDistance = true;
        
        public void FixedUpdate()
        {
            if (isMoveSus)
            {
                MoveSus();
            }
        }

        private void MoveSus()
        {
            var point = pointList[index];
            Vector3 curPos = transform.position;
            Vector3 pos = point.transform.position - curPos;
            float moveDis = speed * Time.deltaTime;
            Vector3 dis = pos.normalized * moveDis;
            //Vector3 newPos = curPos + dis;
            float moveDetail = 0f;
            //float finishDetail = Vector3.Distance(curPos, point.transform.position);

            if (isIgnoreYDistance)
            {
                moveDetail = VectorTool.IgnoreYDistance(curPos, point.transform.position);
            }
            else
            {
                moveDetail = Vector3.Distance(curPos, point.transform.position);
            }
            
            if (moveDis > moveDetail)
            {
                transform.position = point.transform.position;

                index++;
                if (index >= pointList.Count)
                {
                    if (isLoop)
                    {
                        index = 0;
                    }
                    else
                    {
                        isMoveSus = false;
                    }
                }
            }
            else
            {
                transform.position += dis;
            }

            if (isFaceTarget)
            {
                transform.rotation = Quaternion.Lerp(transform.rotation, point.transform.rotation, 0.5f);
            }
        }
    }
}